<template>
  <div class="page_user_mgr">
    <Row class="search_row">
      <Button type="info" icon="md-add" @click="addUser">添加用户</Button>
    </Row>
    <Row class="list_row">
      <Table :columns="columns" border :data="userList"  stripe>
        <template slot-scope="{ row, index }" slot="seq">
          {{(currentPage - 1) * pageSize + index + 1}}
        </template>
      </Table>
      <div class="div_page">
        <Page :total="totalCount" :current="currentPage" :page-size="pageSize"
              show-total show-elevator prev-text="<" next-text=">" @on-change="pageChg"/>
      </div>
    </Row>
    <Drawer title="添加/修改用户" width="400" placement="right" :closable="false" v-model="showDrawer" style="height: 500px;">
      <Form ref="userFormRef" :model="userForm" :rules="userFormValidateRules" :label-width="80">
        <FormItem label="用户名" prop="userName">
          <Input v-model="userForm.userName" placeholder="输入用户名(字母、数字、下划线组成)"></Input>
        </FormItem>
        <FormItem label="昵称" prop="nickName">
          <Input v-model="userForm.nickName" placeholder="昵称"></Input>
        </FormItem>
        <FormItem label="密码" prop="password" v-show="showPwdInput">
          <Input v-model="userForm.password" type="password" icon="md-lock" placeholder="输入密码"></Input>
        </FormItem>
        <FormItem label="确认密码" prop="confirmPassword" v-show="showPwdInput">
          <Input v-model="userForm.confirmPassword" type="password" icon="md-lock" placeholder="输入确认密码"></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="saveOrUpdate" :loading="saveLoading">
            <span v-if="!saveLoading">保存</span>
            <span v-else>保存中....</span>
          </Button>
        </FormItem>
      </Form>
    </Drawer>
    <Drawer title="修改密码" width="400" placement="right" :closable="false" v-model="showChangePwdDrawer"
            style="height: 500px;">
      <Form ref="changePwdFormRef" :model="changePwdForm" :rules="changePwdValidateRules" :label-width="80">
        <FormItem label="新密码" prop="password">
          <Input v-model="changePwdForm.password" type="password" icon="md-lock" placeholder="输入密码"></Input>
        </FormItem>
        <FormItem label="确认密码" prop="confirmPassword">
          <Input v-model="changePwdForm.confirmPassword" type="password" icon="md-lock" placeholder="输入确认密码"></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="changePwd" :loading="pwdLoading">
            <span v-if="!pwdLoading">保存</span>
            <span v-else>保存中....</span>
          </Button>
        </FormItem>
      </Form>
    </Drawer>


    <Drawer title="设置角色" width="300" placement="right" :closable="false" v-model="showRoleDrawer"
            style="height: 500px;">
      <Table stripe :columns="roleCols" :data="roleList" @on-selection-change="roleSelChg" :searchable="false"
             :editable="false"
             ref="userRoleTb"></Table>
      <Row style="text-align: center">
        <Button type="primary" @click="saveUserRole" :loading="roleLoading" style="margin-top: 10px">
          <span v-if="!roleLoading">保存</span>
          <span v-else>保存中....</span>
        </Button>
      </Row>

    </Drawer>
  </div>
</template>

<script>
  import UserApi from '@/api/userApi'
  import RoleApi from '@/api/roleApi'

  export default {
    name: "mg-user-mgr",
    data() {
      const validatePassCheck = (rule, value, callback) => {
        if (value !== this.userForm.password) {
          callback(new Error('两次密码输入不一致！请确认'));
        } else {
          callback();
        }
      };
      const validateChangePassCheck = (rule, value, callback) => {
        if (value !== this.changePwdForm.password) {
          callback(new Error('两次密码输入不一致！请确认'));
        } else {
          callback();
        }
      };
      return {
        leaderList: [],
        showPwdInput: true,
        currentPage: 1,
        totalCount: null,
        pageSize: 10,
        curUserId: '',
        roleLoading: false,
        roleList: [],
        hasSelRoleIdArr: [],//已选角色id数组
        hasInitRoleList: false,
        showRoleDrawer: false,
        saveLoading: false,
        pwdLoading: false,
        showDrawer: false,
        showChangePwdDrawer: false,
        userForm: {
          id: '',
          userName: '',
          nickName: '',
          password: '',
          confirmPassword: ''
        },

        changePwdValidateRules: {
          password: [
            {required: true, message: '用户密码不能为空', trigger: 'blur'},
            {type: 'string', min: 6, max: 18, message: '密码长度必须为6-18位', trigger: 'blur'}
          ],
          confirmPassword: [
            {validator: validateChangePassCheck, trigger: 'blur'}
          ],
        },
        changePwdUserId: '',
        changePwdForm: {
          password: '',
          confirmPassword: ''
        },
        userFormValidateRules: {
          userName: [
            {required: true, message: '用户名不能为空', trigger: 'blur'},
            {type: 'string', pattern: '^[a-zA-Z0-9_]{3,18}$', message: '用户名可由字母、数字、下划线组成,长度必须为3-18位', trigger: 'blur'}
          ],
          nickName: [
            {required: true, message: '昵称不能为空', trigger: 'blur'},
            {type: 'string', pattern: '^[0-9\u4E00-\u9FA5]{2,6}$', message: '昵称可由中文、数字组成，长度必须为2-6位', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'},
            {type: 'string', min: 6, max: 18, message: '密码长度必须为6-18位', trigger: 'blur'}
          ],
          confirmPassword: [
            {validator: validatePassCheck, trigger: 'blur'}
          ],
        },
        userList: [],
        columns: [
          {
            title: '序号',
            slot: 'seq',
            width: 60
          },
          {
            title: '登录名',
            key: 'userName',
            width: 100
          },
          {
            title: '昵称',
            key: 'nickName',
            width: 100
          },
          {
            title: '所属角色',
            key: 'roleNames'
          },
          {
            title: '创建时间',
            key: 'createTime',
            width: 150
          },
          {
            title: '操作',
            key: 'action',
            width: 300,
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'warning',
                    size: 'small'
                  },
                  style: {
                    marginRight: '15px'
                  },
                  on: {
                    click: () => {
                      this.editUser(params.row);
                    }
                  }
                }, '修改'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '15px'
                  },
                  on: {
                    click: () => {
                      this.setRole(params.row);
                    }
                  }
                }, '设置角色'),
                h('Button', {
                  props: {
                    type: 'warning',
                    size: 'small'
                  },
                  style: {
                    marginRight: '15px'
                  },
                  on: {
                    click: () => {
                      this.changePwdUserId = params.row.id
                      this.showChangePwdDrawer = true
                    }
                  }
                }, '重置密码'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  style: {
                    display: params.row.userName === 'admin' ? 'none' : 'inline'
                  },
                  on: {
                    click: () => {
                      this.delUser(params.row);
                    }
                  }
                }, '删除')
              ]);
            }
          }
        ],
        roleCols: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: '角色名称',
            key: 'roleName'
          }
        ]
      }
    },
    methods: {
      pageChg(selPage) {
        this.currentPage = selPage
        this.fetchUserList()
      },
      fetchUserList() {
        this.userList = []
        var param = {'pageSize': this.pageSize, 'currentPage': this.currentPage}
        UserApi.pageResult(param).then(res => {
          this.userList = res.data.data.pageResult.items
          this.totalCount = res.data.data.pageResult.totalCount
        }, error => {
          this.$Message.error(error.response.data.msg);
        })
      },
      saveOrUpdate() {
        this.$refs.userFormRef.validate((valid) => {
          if (valid) {
            this.saveLoading = true;
            UserApi.saveOrUpdate(this.userForm).then(response => {
              this.saveLoading = false;
              this.$Message.success('操作成功')
              this.$refs.userFormRef.resetFields()
              this.showDrawer = false
              this.fetchUserList()
            }, error => {
              this.saveLoading = false;
              this.$Message.error(error.response.data.msg);
            })
          }
        })
      },
      delUser(user) {
        if (user.userName === 'admin') {
          this.$Message.error('admin 为系统帐户, 不允许删除')
          return
        }
        this.$Modal.confirm({
          title: "删除提示",
          content: "确定删除该用户吗？",
          okText: "删除",
          cancelText: "取消",
          onOk: () => {
            this.doDel(user.id);
          }
        });
      },
      doDel(id) {
        UserApi.delete(id).then(res => {
          this.$Message.success('删除成功！')
          this.fetchUserList()
        }, error => {
          this.$Message.error(error.response.data.msg)
        });
      },
      changePwd() {
        this.$refs.changePwdFormRef.validate((valid) => {
          if (valid) {
            this.pwdLoading = true;
            UserApi.resetPwd(this.changePwdUserId, this.changePwdForm.password, this.changePwdForm.confirmPassword).then(response => {
              this.pwdLoading = false;
              this.$Message.success('密码重置成功！')
              this.$refs.userFormRef.resetFields()
              this.showChangePwdDrawer = false
              this.changePwdForm.password = "";
              this.changePwdForm.confirmPassword = "";
            }, error => {
              this.pwdLoading = false;
              this.message = error.response.data.msg
            })
          }
        })
      },
      searchByLeaderName(name) {
        UserApi.search(this.userForm.id, name).then(response => {
          var srcList = response.data.data.pageResult.items;
          var retList = []
          if (null != srcList && srcList.length > 0) {
            for (var i = 0; i < srcList.length; i++) {
              retList.push(srcList[i].userName + "," + srcList[i].enName + "," + srcList[i].cnName)
            }
          } else {
            retList.push("无匹配用户");
          }
          this.leaderList = retList

        }, error => {
          this.message = error.response.data.msg
        })
      },
      onLeaderNameSel(value) {
        const arr = value.split(",")
        this.userForm.directLeader = arr[0]
        this.userForm.leaderName = arr[1]
      },
      addUser() {
        this.showDrawer = true
        this.showPwdInput = true
        this.userForm = {
          id: '',
          userName: '',
          nickName: '',
          password: '',
          confirmPassword: ''
        }
      },
      editUser(row) {
        this.showDrawer = true
        this.showPwdInput = false;
        console.log("用户信息：" + JSON.stringify(row))
        const leaderName = null != row.leaderName ? row.leaderName : ''
        this.userForm = {
          id: row.id,
          userName: row.userName,
          nickName: row.nickName,
          password: '111111',
          confirmPassword: '111111'
        }
      },
      setRole(row) {
        this.curUserId = row.id;
        this.showRoleDrawer = true;
        this.roleList = [];
        this.hasSelRoleIdArr = [];
        RoleApi.queryUserRoleList(this.curUserId).then(response => {
          var retList = response.data.data.roleList;
          if (null != retList && retList.length > 0) {
            for (var i = 0; i < retList.length; i++) {
              var obj = retList[i];
              if (obj.checked == "checked") {
                obj._checked = true;
                this.hasSelRoleIdArr.push(obj.id);
              }
            }
          }
          this.roleList = retList
        }, error => {
          this.$Message.error(error.response.data.msg);
        })
      },
      /**
       * 表格多选框选择改变事件
       * @param selection：当前已选项目
       */
      roleSelChg(selection) {
        this.hasSelRoleIdArr = [];
        for (var i = 0; i < selection.length; i++) {
          var obj = selection[i];
          this.hasSelRoleIdArr.push(obj.id);
        }
      },
      saveUserRole() {
        if (this.hasSelRoleIdArr.length == 0) {
          this.$Message.error("请至少选择一个角色！");
          return;
        }
        this.roleLoading = true;
        UserApi.bindUserRole(this.curUserId, this.hasSelRoleIdArr.join(",")).then(response => {
          this.roleLoading = false;
          this.showRoleDrawer = false;
          this.$Message.success("设置成功！");
          this.fetchUserList()
        }, error => {
          this.roleLoading = false;
          this.$Message.error(error.response.data.msg);
        })
      }
    },
    created() {
      this.currentPage = 1
      this.fetchUserList()
    }
  }
</script>
